package org.jeecg.modules.act.wx;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.wx.Const;
import org.jeecg.common.wx.DateUtil;
import org.jeecg.common.wx.WxUserInfo;
import org.jeecg.modules.act.dto.MsgPush;
import org.jeecg.modules.act.dto.SignUp;
import org.jeecg.modules.act.dto.UserRecordDto;
import org.jeecg.modules.act.entity.*;
import org.jeecg.modules.act.service.*;
import org.jeecg.modules.act.vo.ActivityVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 活动管理controller
 */
@Api(tags = "wx_小程序活动管理接口")
@RestController
@RequestMapping("/wx/")
@Slf4j
public class WxActivityController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActMatterService matterService;
    @Autowired
    private IActShareService shareService;
    @Resource
    private IActUserService userService;
    @Resource
    private IActUserRecordService recordService;
    @Resource
    private IActFormService formService;
    @Resource
    private IActUsermatterService usermatterService;


    @ApiOperation(value = "活动详情", notes = "活动详情")
    @GetMapping("activityDetail")
    @ApiImplicitParam(name = "actId", value = "活动id", required = true)
    public Result activityDetail(String actId, String userId) {
        return activityService.detail(actId, userId);
    }

    @ApiOperation(value = "参加活动人数", notes = "参加活动的人数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "actId", value = "活动id", required = true),
            @ApiImplicitParam(name = "orderType", value = "排序方式 1 报名时间desc 2 报名时间asc 3 修改时间desc")
    })
    @GetMapping("actUsers")
    public Result actUsers(String actId,
                           @RequestParam(value = "orderType", defaultValue = "1") Integer orderType) {
        return activityService.actUsers(actId, orderType);
    }

    @ApiOperation(value = "报名申请单", notes = "报名申请单")
    @GetMapping("application")
    @ApiImplicitParam(name = "actId", value = "活动id", required = true)
    public Result application(String actId, String userId) {
        return matterService.findAllByActId(actId, userId);
    }

    @ApiOperation(value = "报名", notes = "报名")
    @PostMapping("signUp")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "userId", value = "用户id"),
            @ApiImplicitParam(required = true, name = "actId", value = "活动id"),
            @ApiImplicitParam(name = "shareId", value = "分享的id"),
            @ApiImplicitParam(name = "type", value = "分享的途径", defaultValue = "1")
    })
    public Result signUp(@RequestBody List<SignUp> signUps,
                         String userId,
                         String actId,
                         String shareId,
                         Integer type) {
        return activityService.signUp(signUps, userId, actId, shareId, type);
    }


    @ApiOperation(value = "活动分享", notes = "活动分享")
    @PostMapping("shareAct")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "actId", value = "活动id", required = true),
            @ApiImplicitParam(name = "userId", value = "分享人id", required = true),
            @ApiImplicitParam(name = "type", value = "分享类型 1朋友圈 2分享给好友 3生成二维码分享 4复制链接", required = true)
    })
    public Result shareAct(String actId, String userId, Integer type) {
        Result result = new Result();
        ActShare share = new ActShare();
        share.setUserId(userId);
        share.setActId(actId);
        share.setShareType(type);
        boolean b = shareService.save(share);
        if (b) {
            result.setSuccess(true);
            result.setMessage("分享成功");
        } else {
            result.setSuccess(false);
            result.setCode(1);
        }
        return result;
    }


    @ApiOperation(value = "我的报名", notes = "我的报名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "条数", defaultValue = "10"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    })
    @GetMapping("myJoinRecord")
    public Result myJoinRecord(String userId,
                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<ActivityVo>> result = new Result<>();
        Page<ActivityVo> page = new Page<>(pageNo, pageSize);
        IPage<ActivityVo> activityVoIPage = activityService.myJoinRecord(userId, page);
        result.setResult(activityVoIPage);
        result.setSuccess(true);
        return result;
    }

    //报名时存报名者的相关formId
    @ApiOperation(value = "保存或者更新formId", notes = "保存或者更新formId")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "表单id", name = "formId", required = true),
            @ApiImplicitParam(value = "活动id", name = "actId", required = true),
            @ApiImplicitParam(value = "用户id", name = "userId", required = true),
    })
    @PostMapping("saveOrUpdateFormId")
    public Result saveOrUpdateFormId(String formId, String actId, String userId, String openId) {
        return activityService.saveOrUpdateFormId(formId, actId, userId, openId);
    }

    @ApiOperation(value = "推送", notes = "推送")
    @PostMapping("push")
    public void push(@RequestBody MsgPush msg) {

        Activity activity = activityService.getById(msg.getActId());
        String openId = null;
        String keyword2 = null;
        String keyword3 = null;
        String keyword4 = null;
        String templateId = null;

        //内容修改通知
        if (1 == msg.getType()) {
            keyword3 = DateUtil.date2Str(new Date());
            keyword2 = msg.getNote();
            templateId = Const.UPDATE_MSG_TEMPLATE_ID;
            QueryWrapper<ActUserRecord> wrapper = new QueryWrapper<>(new ActUserRecord());
            wrapper.eq("act_id", msg.getActId());
            List<ActUserRecord> records = recordService.list(wrapper);
            String finalTemplateId = templateId;
            String finalKeyword2 = keyword2;
            String finalKeyword3 = keyword3;
            String finalKeyword4 = keyword4;
            records.forEach(r -> {
                try {
                    ActUser actUser1 = userService.getById(r.getUserId());
                    QueryWrapper<ActForm> formQueryWrapper = new QueryWrapper<>(new ActForm());
                    formQueryWrapper.eq("user_id", r.getUserId());
                    formQueryWrapper.eq("act_id", msg.getActId());
                    List<ActForm> formList = formService.list(formQueryWrapper);
                    String userFormId = formList.get(0).getFormId();
                    WxUserInfo.isPush(actUser1.getOpenid(),
                            userFormId, finalTemplateId,
                            activity.getTitle(), finalKeyword2,
                            finalKeyword3, finalKeyword4, msg.getUrl());
                    formQueryWrapper.eq("form_id", userFormId);
                    formService.remove(formQueryWrapper);
                    log.info("openId:{}", actUser1.getOpenid());
                    log.info("formId:{}", userFormId);
                    log.info("templateId:{}", finalTemplateId);
                    log.info("keyword1Value:{}", activity.getTitle());
                    log.info("keyword2Value:{}", finalKeyword3);
                    log.info("keyword3Value:{}", finalKeyword2);
                    log.info("keyword4Value:{}", finalKeyword4);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("error:{}", "推送错误");
                }
            });

        }
        //报名审核通知 发给被审核的人
        ActUser actUser = userService.getById(msg.getUserId());
        if (2 == msg.getType()) {
            QueryWrapper<ActForm> formQueryWrapper = new QueryWrapper<>(new ActForm());
            formQueryWrapper.eq("user_id", msg.getUserId());
            List<ActForm> formList = formService.list(formQueryWrapper);
            String userFormId = formList.get(0).getFormId();
            keyword3 = actUser.getUsername();
            keyword4 = msg.getNote();
            templateId = Const.SIGIN_TEMPLATE_ID;
            if (2 == msg.getStatus()) {
                keyword2 = "审核通过";
            } else {
                keyword2 = "审核未通过";
            }
            openId = actUser.getOpenid();
            WxUserInfo.isPush(openId, userFormId, templateId, activity.getTitle(), keyword2, keyword3, keyword4, msg.getUrl());
            formQueryWrapper.eq("form_id", userFormId);
            formService.remove(formQueryWrapper);
            log.info("openId:{}", openId);
            log.info("formId:{}", userFormId);
            log.info("templateId:{}", templateId);
            log.info("keyword1Value:{}", activity.getTitle());
            log.info("keyword2Value:{}", keyword2);
            log.info("keyword3Value:{}", keyword3);
            log.info("keyword4Value:{}", keyword4);
        }
        //报名通知 发给管理员
        if (3 == msg.getType()) {
            keyword2 = actUser.getUsername();
            keyword3 = "有新用户报名了,请及时审核";
            keyword4 = msg.getNote();
            templateId = Const.CHECK_SIGIN_TEMPLATE_ID;
            ActUser manger = userService.getById(activity.getUserId());
            openId = manger.getOpenid();
            QueryWrapper<ActForm> queryWrapper = new QueryWrapper<>(new ActForm());
            queryWrapper.eq("user_id", activity.getUserId());
            List<ActForm> formList = formService.list(queryWrapper);
            String formId = formList.get(0).getFormId();
            WxUserInfo.isPush(openId, formId, templateId, activity.getTitle(), keyword2, keyword3, keyword4, msg.getUrl());
            QueryWrapper<ActForm> formQueryWrapper = new QueryWrapper<>(new ActForm());
            formQueryWrapper.eq("form_id", formId);
            formService.remove(formQueryWrapper);
            log.info("openId:{}", openId);
            log.info("formId:{}", formId);
            log.info("templateId:{}", templateId);
            log.info("keyword1Value:{}", activity.getTitle());
            log.info("keyword2Value:{}", keyword2);
            log.info("keyword3Value:{}", keyword3);
            log.info("keyword4Value:{}", keyword4);
        }
    }

    @ApiOperation(value = "保存用户记录", notes = "保存用户信息")
    @PostMapping("saveUserRecord")
    public Result saveUserRecord(@RequestBody List<UserRecordDto> dtos) {
        Result result = new Result();
        if (CollectionUtils.isEmpty(dtos)) {
            result.setResult(null);
            return result;
        }
        usermatterService.saveOrUpdateBatch(dto2ActUserMatter(dtos));
        return result;
    }

    private List<ActUsermatter> dto2ActUserMatter(List<UserRecordDto> dtos) {
        List<ActUsermatter> usermatters = new ArrayList<>();
        dtos.forEach(d -> {
            ActUsermatter m = new ActUsermatter();
            BeanUtils.copyProperties(d, m);
            m.setId(d.getUmId());
            usermatters.add(m);
        });
        return usermatters;
    }


    @ApiOperation(value = "所有活动", notes = "所有活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "条数", defaultValue = "10")
    })
    @GetMapping("allActivities")
    public Result allActivities(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<ActivityVo>> result = new Result<>();
        Page<ActivityVo> page = new Page<>(pageNo, pageSize);
        IPage<ActivityVo> activityVoIPage = activityService.allActivities(page);
        result.setResult(activityVoIPage);
        result.setSuccess(true);
        return result;
    }
}
